<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :modal-style="{ maxWidth: '520px' }"
    width="90%"
    @before-ok="save"
    @close="reset"
  >
    <a-form :model="form" :auto-label-width="true" layout="horizontal">
      <a-space direction="vertical" :style="{ width: '300px' }" style="margin: 0 auto">
        <a-form-item field="name" :style="{ width: '300px' }" label="裁判">
          <a-select v-model="selectedOptions" style="margin: 0 auto" placeholder="请选择裁判" multiple :filter-option="false">
            <a-option v-for="item of options" :value="item.id">{{item.username}}</a-option>
          </a-select>
        </a-form-item>
      </a-space>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import {getProjectReferee, addProjectReferee, updateProjectReferee, listRefereeUser} from '@/apis'
import { useForm } from '@/hooks'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改项目裁判' : '新增项目裁判'))


const { form, resetForm } = useForm({
  refereeId: '',
  refereeName: '',
})


const selectedOptions = ref([]);
const options = ref();
onMounted(() => {
  search()
})
const search =async () => {
    // 从后端获取数据
    const res = await listRefereeUser();
    options.value = res.data as any;
};

// 重置
const reset = () => {
  resetForm()
}

const visible = ref(false)
// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const res = await getProjectReferee(id)
  Object.assign(form, res.data)
  visible.value = true
}

// 保存
const save = async () => {
  try {
    if (isUpdate.value) {
      await updateProjectReferee(form, dataId.value)
      Message.success('修改成功')
    } else {
      //todo 添加裁判
      console.log(selectedOptions.value)
      // await addProjectReferee(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onAdd, onUpdate })
</script>
